package qmlt.dataset.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import qmlt.dataset.Instance;

public class DataSetUtils
{
	public static List<Object> getFeatureColumn(List<Instance> instances, int i)
	{
		List<Object> rst = new ArrayList<Object>();
		for (Instance inst : instances)
		{
			rst.add(inst.getFeatures().get(i));
		}
		return rst;
	}

	public static List<Object> getTargetColumn(List<Instance> instances)
	{
		List<Object> rst = new ArrayList<Object>();
		for (Instance inst : instances)
		{
			rst.add(inst.getTarget());
		}
		return rst;
	}

	/**
	 * Sort instances into sublists based on their targets, and return a mapping from the target value
	 * to the sublist.
	 * 
	 * @param instances
	 * @return
	 */
	public static Map<Object, List<Instance>> asMap(List<Instance> instances)
	{
		Map<Object, List<Instance>> map = new HashMap<Object, List<Instance>>();

		for (Instance inst : instances)
		{
			Object target = (Object) inst.getTarget();
			if (map.containsKey(target))
			{
				map.get(target).add(inst);
			}
			else
			{
				List<Instance> newList = new ArrayList<Instance>();
				newList.add(inst);
				map.put(target, newList);
			}
		}

		return map;
	}

	/**
	 * 
	 * Sort instances into sublists based on their i-th feature, and return a mapping from the feature
	 * value to the sublist.
	 * 
	 * @param instances
	 * @param i
	 * @return
	 */
	public static Map<Object, List<Instance>> asMap(List<Instance> instances, int i)
	{
		Map<Object, List<Instance>> map = new HashMap<Object, List<Instance>>();

		for (Instance inst : instances)
		{
			Object value = (Object) inst.getFeatures().get(i);

			if (map.containsKey(value))
			{
				map.get(value).add(inst);
			}
			else
			{
				List<Instance> newList = new ArrayList<Instance>();
				newList.add(inst);
				map.put(value, newList);
			}
		}

		return map;
	}

	public static Object findMajorClass(List<Instance> instances)
	{
		List<Object> classValues = getTargetColumn(instances);
		return ListUtils.findMajor(classValues);
	}

}
